package com.djhu.freepartner.web.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.djhu.freepartner.bean.FavouritePost;
import com.djhu.freepartner.bean.PartnerMessage;
import com.djhu.freepartner.bean.PartnerPost;
import com.djhu.freepartner.bean.PartnerUser;
import com.djhu.freepartner.core.RestRsp;
import com.djhu.freepartner.core.Status;
import com.djhu.freepartner.core.exception.ServiceException;
import com.djhu.freepartner.service.IFavouritePostService;
import com.djhu.freepartner.service.IPartnerMessageService;
import com.djhu.freepartner.service.IPartnerPostService;
import com.djhu.freepartner.service.IPartnerUserService;
import com.djhu.freepartner.utils.DateUtils;
import com.djhu.freepartner.web.control.model.PostSearchModel;
import com.djhu.freepartner.web.control.model.ReadPostRequest;
import com.djhu.freepartner.web.service.BonuspointsService;
import com.djhu.freepartner.web.service.IUserMessageService;
import com.djhu.freepartner.web.service.PostService;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class PostServiceImpl implements PostService {

    private static final String POSTCHECK = "POSTCHECK";

    private static final String POSTREAD = "POSTREAD";

    private static final String CONTENTFORMAT = "用户 %s 在  阅读了你的帖子 %s,请注意查看!!!!";

    @Value("${spring.freepartner.read_account:10}")
    private int read_account = 10;

    @Autowired
    private IPartnerUserService partnerUserService;


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IUserMessageService userMessageService;

//    @Autowired
//    private IPartnerMessageService messageService;

    @Autowired
    private BonuspointsService bonuspointsService;

    @Autowired
    private IPartnerPostService partnerPostService;


    @Autowired
    private IFavouritePostService favouritePostService;

    @Value("${spring.feepartner.freepostnum:3}")
    private Integer freePostNum = 5;

    @Value("${spring.feepartner.freereadnum:5}")
    private Integer freeReadNum = 5;

    @Override
    public RestRsp publishpostCheck(String userid) {
        RestRsp restRsp = partnerUserService.checkUser(userid);
        //用户检验失败 直接返回
        if (restRsp.getCode() != Status.SUCCESS.getCode()){
            return restRsp;
        }

        String today = DateUtils.today();
        String key = Joiner.on("_").join(today,POSTCHECK);
        if (redisTemplate.opsForHash().hasKey(key,userid)){
            long size = Long.parseLong(String.valueOf(redisTemplate.opsForHash().get(key,userid)));
            if (size > freePostNum) {
                log.info("user has post tomuch post today,useid is {}",userid);
                restRsp.setCode(Status.LARGER_THAN_MAXPOST.getCode());
                restRsp.setMsg(Status.LARGER_THAN_MAXPOST.getDesc());
                return restRsp;
            }
        }else {
            redisTemplate.opsForHash().put(key,userid,String.valueOf(1));
            redisTemplate.expire(key,1,TimeUnit.DAYS);
        }
        restRsp.setCode(Status.SUCCESS.getCode());
        restRsp.setMsg("可以免费发帖!!!");
        return restRsp;
    }

    @Override
    public RestRsp readpostCheck(String userid, String postid) {
        RestRsp restRsp = partnerUserService.checkUser(userid);
        //用户检验失败 直接返回
        if (restRsp.getCode() != Status.SUCCESS.getCode()){
            log.info("user check is error!!,userid is {}",userid);
            return restRsp;
        }

        PartnerPost partnerPost  = partnerPostService.selectById(postid);
        //帖子不存在
        if (partnerPost == null){
            log.info("post is not found,post id is {}",postid);
            restRsp.setCode(Status.NOT_FOUND.getCode());
            return restRsp;
        }

        if (userid.equals(partnerPost.getCreateUserId())){
            //自己发布的帖子
            log.info("post is user post ,do not count!!,postid is  {},userid is {}",postid,userid);
            return restRsp;
        }else {
            String key = Joiner.on("_").join(userid,DateUtils.today(),POSTREAD).toLowerCase();
            log.info("post check is {}",key);
            long  size = redisTemplate.opsForSet().size(key);
            if (size > freeReadNum){
                restRsp.setCode(Status.LARGER_THAN_MAXREAD.getCode());
                restRsp.setMsg(Status.LARGER_THAN_MAXREAD.getDesc());
                return restRsp;
            }
        }
        restRsp = new RestRsp(Status.SUCCESS);
        return restRsp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestRsp pubishPost(PartnerPost partnerPost, boolean isFree) throws ServiceException {
        //发布帖子
        boolean isInsert = partnerPostService.insert(partnerPost);
        if (!isInsert){
            throw new ServiceException(Status.BAD_REQUEST_BODY.getDesc(),Status.BAD_REQUEST_BODY.getCode());
        }

        /**
         * 加入每天发帖的计数
         */
        String today = DateUtils.today();
        String key = Joiner.on("_").join(today,POSTCHECK);
        String userid = partnerPost.getCreateUserId();
        if ( redisTemplate.opsForHash().hasKey(key,partnerPost.getCreateUserId())) {
            redisTemplate.opsForHash().increment(key, partnerPost.getCreateUserId(), 1);
        }else {
            redisTemplate.opsForHash().put(key,userid,String.valueOf(1));
        }
        /**
         * 暂时不操作 发帖免费
         */
        if (isFree){

        }
        //扣除积分
        RestRsp restRsp = new RestRsp(Status.SUCCESS);
        return restRsp;
    }

    @Override
    public Page<PartnerPost> searchPost(PostSearchModel postSearchModel) {
        Wrapper wrapper = new EntityWrapper<PartnerPost>();
        if (StringUtils.isNotEmpty(postSearchModel.getPartnerProvinceCode())){
            wrapper = wrapper.eq("partner_province_code",postSearchModel.getPartnerProvinceCode());
        }
        if (StringUtils.isNotEmpty(postSearchModel.getPartnerCityCode())){
            wrapper = wrapper.eq("partner_city_code",postSearchModel.getPartnerCityCode());
        }
        if (StringUtils.isNotEmpty(postSearchModel.getPartnerCountyCode())){
            wrapper = wrapper.eq("partner_county_code",postSearchModel.getPartnerCountyCode());
        }

        if (StringUtils.isNotEmpty(postSearchModel.getPartnerType())){
            wrapper = wrapper.eq("partner_type",postSearchModel.getPartnerType());
        }
        if (StringUtils.isNotEmpty(postSearchModel.getSex())){
            wrapper = wrapper.eq("sex",postSearchModel.getSex());
        }

        if (StringUtils.isNotEmpty(postSearchModel.getPartnerPayCode())){
            wrapper = wrapper.eq("partner_pay_code",postSearchModel.getPartnerPayCode());
        }

        if (postSearchModel.getMaxage() <= 100 &&  postSearchModel.getMinage()  >=0){
            wrapper = wrapper.between("age",postSearchModel.getMinage(),postSearchModel.getMaxage());
        }
        wrapper = wrapper.orderBy(postSearchModel.getOrderBy());

        Page page = new Page(postSearchModel.getPagenum(),postSearchModel.getPagesize());

        Page selectPage = partnerPostService.selectPage(page,wrapper);
        return selectPage;
    }



    @Override
    @Transactional
    public PartnerPost readPost(ReadPostRequest readPostRequest) throws ServiceException {
        String postId = readPostRequest.getPostid();
        PartnerPost partnerPost = partnerPostService.selectById(postId);
        if (partnerPost == null){
            log.error("post is not exist!!!!,id is {}",postId);
            throw new ServiceException(Status.NOT_FOUND);
        }

        //自己发的帖子
        if (partnerPost.getCreateUserId().equals(readPostRequest.getUserid())){
            return partnerPost;
        }

        //增加阅读数
        Integer browse = partnerPost.getBrowse();
        if (browse == null){
            browse = 0;
        }else {
            browse = browse + 1;
        }
        PartnerPost updatePost = new PartnerPost();
        updatePost.setPostId(partnerPost.getPostId());
        updatePost.setBrowse(browse);
        partnerPostService.updateById(updatePost);

        /**
         * 免费看 增加当天阅读记录 付费看 不添加查看记录 扣分
         */
        PartnerUser readUser = partnerUserService.selectById(readPostRequest.getUserid());
        if (readPostRequest.isFree()) {
            String key = Joiner.on("_").join(readPostRequest.getUserid(),DateUtils.today(),POSTREAD).toLowerCase();
            this.redisTemplate.opsForSet().add(key, readPostRequest.getPostid());
        }else {
            bonuspointsService.consume(readUser.getUserid(),read_account,"查看帖子");
//            int account = readUser.getAccount() - read_account;
//            readUser.setAccount(account);
//            readUser.updateById();



        }
        //添加阅读消息  到 消息表
//        PartnerUser readUser = partnerUserService.selectById(readPostRequest.getUserid());
        String content = String.format(CONTENTFORMAT,readUser.getUsername(),DateUtils.now(),partnerPost.getTitle());
        PartnerMessage message = new PartnerMessage();
        message.setContent(content);
        message.setReadFlag("0");
        message.setType("notice");
        message.setPostid(partnerPost.getPostId());
        message.setUserId(readPostRequest.getUserid());
        message.setCreateUserId(readUser.getUserid());
        userMessageService.insert(message);
        return partnerPost;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deletePost(PostSearchModel postSearchModel) {
        //删除帖子信息
        String postId = postSearchModel.getPostid();
        partnerPostService.deleteById(postId);
        Wrapper<FavouritePost> wrpper = new EntityWrapper<>();
        //删除关注列表中的信息
        wrpper.eq("postid",postId);
        favouritePostService.delete(wrpper);
        return true;
    }

    @Override
    public List<PartnerPost> list(String userid) {
        Wrapper<PartnerPost> wrapper = new EntityWrapper<>();
        wrapper.eq("create_user_id",userid);
        List<PartnerPost> postList =  partnerPostService.selectList(wrapper);
        log.info("list method,postlist size is {},userid is {}",postList.size(),userid);
        return postList;
    }


}
